/*
	|=====|	|	|
	|	|	|	|
	|=====|	|=====|
	|	|	|	|
	|=====|	|	|
	
	BASEHACK
	Code by "Brwarner" STEAM_0_1_12243023
	
	Functions for serverside phases (Build and Combat)
*/

//Phase information (local vars)

//Current phase
phaseNum = 0;

//Countdown timer for phases
phaseTimer = maxBuildPhase;

//Called each time there is a phase change
function PhaseChanged()
	//Change phase variables
	if(phaseNum == 0) then phaseNum = 1;
	else phaseNum = 0; end
	if(phaseNum == 0) then phaseTimer = maxBuildPhase;
	else phaseTimer = maxCombatPhase; end
	
	//For each player, reset their weapons
	for key, val in pairs(player.GetAll()) do
		hook.Call("PlayerRespawn", nil, val);
	end
	
	local dividers = ents.FindByClass("func_divider");
	for key, val in pairs(dividers) do
		if(phaseNum == 0) then
			val:SetNotSolid(false);
			/*val:SetVisible(true);*/
		else
			val:SetNotSolid(true);
			/*val:SetVisible(false);*/
		end
	end
	
	//Unhack all blocks
	local blocks_r = hook.Call("GetTeamBlocks", nil, 1);
	local blocks_c = hook.Call("GetTeamBlocks", nil, 2);
	table.Add(blocks_r, blocks_c);
	
	for key, val in pairs(blocks_r) do
		ents.GetByIndex(val):ForceHackEnd();
	end
end

//Returns the current phase number
function CurrentPhase()
	return phaseNum;
end
hook.Add("GetPhaseNumber", "BHCurrentPhase", CurrentPhase);

//Time of last call of think function
local lastThink = CurTime();

//Called every frame
function Think()
	//Decrease the phase time by the time past
	phaseTimer = phaseTimer - (CurTime() - lastThink);
	
	//Change time of last think call to now
	lastThink = CurTime();
	
	//Find out if a change of phase is needed
	local change = false;
	if(phaseTimer <= 0) then change = true; end
	
	//Send user message to all players
	local rp = RecipientFilter();
	rp:AddAllPlayers();
	
	//If we need to change
	if(change) then 
		//Update phase ID and time
		PhaseChanged();
	end
	
	//Tell each player the new time
	umsg.Start("timeChange", rp);
		umsg.Long(phaseNum);
		umsg.Long(phaseTimer);
	umsg.End();
end
hook.Add("Think", "BHThink", Think);

//Allows admins to switch phases at will
if(SERVER) then
function ForceSwitchPhase(ply, cmd, args)
	if(ply:IsAdmin()) then PhaseChanged(); end
end
concommand.Add("ChangePhase", ForceSwitchPhase);

end